// ImagePreviewActivity.kt
package com.help10000.rms.ui.activitys

import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.amir.common.utils.LogUtils
import com.amir.common.utils.ToastUtil
import com.bumptech.glide.Glide
import com.github.chrisbanes.photoview.PhotoView
import com.help10000.rms.R
import org.json.JSONArray
//图片预览页面
class ImagePreviewActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_preview)

        val viewPager: ViewPager2 = findViewById(R.id.view_pager)
        val btnClose: ImageButton = findViewById(R.id.btn_close)
        val btnSave: TextView = findViewById(R.id.btn_save)
        val pageIndicator: TextView = findViewById(R.id.tv_page_indicator)


        // 解析 JS 传过来的 JSON 数组
        val jsonArray = intent.getStringExtra("imageUris") ?: "[]"
        val paths = mutableListOf<String>()
        JSONArray(jsonArray).let { arr ->
            for (i in 0 until arr.length()) {
                paths.add(arr.getString(i))
            }
        }


        LogUtils.I("TrackMenu ImagePreviewActivity paths ${paths.toString()}")

        // 设置 ViewPager2 适配器
        viewPager.adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
                val photoView = PhotoView(parent.context).apply {
                    layoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                    maximumScale = 5f
                }
                return object : RecyclerView.ViewHolder(photoView) {}
            }

            override fun getItemCount(): Int = paths.size

            override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
                val url = paths[position]
                val uri = when {
                    url.startsWith("content://") || url.startsWith("http") ->
                        Uri.parse(url)
                    else ->
                        Uri.parse("file://$url")
                }
                val photoView = holder.itemView as PhotoView
                Glide.with(photoView.context)
                    .load(uri)
                    .error(R.drawable.ic_error_placeholder)
                    .into(photoView)
            }
        }

        // 文本页码指示
        if (paths.size <= 1) {
            pageIndicator.visibility = View.GONE
        } else {
            pageIndicator.text = "1/${paths.size}"
            viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    pageIndicator.text = "${position + 1}/${paths.size}"
                }
            })
        }

        // 关闭按钮
        btnClose.setOnClickListener { finish() }
        btnSave.setOnClickListener {
            val position = viewPager.currentItem
            val viewHolder = (viewPager.getChildAt(0) as RecyclerView).findViewHolderForAdapterPosition(position)
            val photoView = viewHolder?.itemView as? PhotoView

            val drawable = photoView?.drawable
            if (drawable is BitmapDrawable) {
                val bitmap = drawable.bitmap
                saveImageToGallery(bitmap)
            } else {
                ToastUtil.show("图片尚未加载完成")
            }
        }
    }

    private fun saveImageToGallery(bitmap: Bitmap) {
        val filename = "IMG_${System.currentTimeMillis()}.jpg"
        val resolver = contentResolver

        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, filename)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
                put(MediaStore.Images.Media.IS_PENDING, 1)
            }
        }

        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        uri?.let {
            resolver.openOutputStream(it)?.use { outputStream ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                contentValues.clear()
                contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
                resolver.update(it, contentValues, null, null)
            }
            ToastUtil.show("图片已保存到相册",)
        } ?: ToastUtil.show("保存失败")
    }



    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) enterImmersiveMode()
    }

    private fun enterImmersiveMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.setDecorFitsSystemWindows(false)
            window.insetsController?.let { controller ->
                controller.hide(
                    WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars()
                )
                controller.systemBarsBehavior =
                    WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            }
        } else {
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_IMMERSIVE
                            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_FULLSCREEN
                    )
        }
    }
}
